<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue';
import { useEditor, EditorContent } from '@tiptap/vue-3';
import StarterKit from '@tiptap/starter-kit';
import Placeholder from '@tiptap/extension-placeholder';
import TextStyle from "@tiptap/extension-text-style";
import { Color } from '@tiptap/extension-color';
import { postService } from "@/services/PostService.js";
import { useRouter } from "vue-router";
import { userManager } from "@/utils/user.js";
import creditService from '@/services/creditService';
import { ElInput, ElButton, ElSelect, ElOption, ElMessage } from 'element-plus';
import { methods } from '@/utils/methods';


const title = ref('');
const router = useRouter();
const fontSizes = ['12px', '14px', '16px', '18px', '24px', '32px'];
const tags = ref([]); // 功能保留
const newTagInput = ref(''); // 功能保留
const todayPostArticleNum=ref(0)//今天已发送的帖子文章数

const editor = useEditor({
  content: '',
  extensions: [
    StarterKit.configure({ textStyle: false }),
    Placeholder.configure({ placeholder: '分享、吐槽、提问，说你想说的～' }),
    TextStyle.extend({
      addAttributes() {
        return {
          ...this.parent?.(),
          fontSize: {
            default: null,
            parseHTML: element => element.style.fontSize,
            renderHTML: attributes => (attributes.fontSize ? { style: `font-size: ${attributes.fontSize}` } : {}),
          },
        };
      },
    }),
    Color,
  ],
  editorProps: { attributes: { class: 'prose-mirror-editor' } },
});
onMounted(() => {
  postService.getTodayPostArticleNum(userManager.getUserId(),(res)=>{
    todayPostArticleNum.value=res.data
  })
 
});

const setFontSize = (size) => {
  if (!editor.value) return;
  size === '' ? editor.value.chain().focus().setMark('textStyle', { fontSize: null }).run() : editor.value.chain().focus().setMark('textStyle', { fontSize: size }).run();
};

const insertTemplate = (type) => {
  if (!editor.value) return;
  let templateHtml = '';
  switch (type) {
    case 'interview':
      templateHtml = `<h2>面试问题记录</h2><strong>📍 面试公司：</strong><p></p><strong>🕔 面试时间：</strong><p></p><strong>💻 面试岗位：</strong><p></p><strong>❓ 面试问题：</strong><p></p><strong>🙌 面试感想：</strong><p>#面试问题记录#</p>`;
      break;
    case 'offer':
      templateHtml = `<strong>🙋 个人背景：</strong><p>（学校、学历、专业、实习经历等）</p><strong>🥭 Offer 1:</strong><p><strong>公司：</strong></p><p><strong>岗位：</strong></p><p><strong>薪资：</strong></p><p><strong>地点：</strong></p><p>#offer比较#</p>`;
      break;
    case 'review':
      templateHtml = `<strong>🎓 学历背景：</strong><p>（学校、专业、绩点等信息）</p><strong>🎯 意向职位：</strong><p>（您期望求职的目标岗位）</p><strong>💼 求职类型：</strong><p>（校招、实习或社招）</p><strong>🔑 遇到的问题：</strong><p>（希望大家从哪些方面给您建议或指导）</p><hr><blockquote><p>请在这里附上您的简历内容（为了保护隐私，建议使用截图并抹去姓名、联系方式等敏感信息）</p></blockquote><p>#我的简历长这样#</p>`;
      break;
  }
  editor.value.commands.insertContent(templateHtml);
  editor.value.commands.focus();
};

const publishArticle = async () => {
  if (!title.value.trim() || editor.value.isEmpty) {
    ElMessage.warning('标题和内容都不能为空！');
    return;
  }
  const articleData = {
    author: userManager.getUserId(),
    title: title.value,
    content: editor.value.getHTML(),
    tags: tags.value,
  };
  try {
    await postService.createArticle(articleData);
   
    todayPostArticleNum.value++;
    ElMessage.success('发布成功');
    if(todayPostArticleNum.value<=5){
      creditService.addNewCredit(5,null,methods.FORUM_ACTIVITY,userManager.getUserId(),(res)=>{
        ElMessage.success('学分增加5分还剩'+(5-todayPostArticleNum.value)+'次加学分的机会');
      })
    }

    router.push(`/forum`);
  } catch (error) {
    console.error("发布失败:", error);
    ElMessage.error("发布失败，请重试。");
  }
};

onBeforeUnmount(() => editor.value?.destroy());
</script>

<template>
  <div class="editor-page-background">
    <div class="editor-panel">
      <div class="editor-header">
        <el-input v-model="title" placeholder="请输入文章标题..." size="large" :borderless="true" class="title-input"/>
        <div class="header-actions">
          <el-button>保存草稿</el-button>
          <el-button type="primary" @click="publishArticle">发布文章</el-button>
        </div>
      </div>
      <div v-if="editor" class="tiptap-container">
        <div class="editor-toolbar">
          <el-button text @click="editor.chain().focus().toggleBold().run()" :type="editor.isActive('bold') ? 'primary' : ''" title="加粗"><b>B</b></el-button>
          <el-button text @click="editor.chain().focus().toggleItalic().run()" :type="editor.isActive('italic') ? 'primary' : ''" title="斜体"><i>I</i></el-button>
          <el-button text @click="editor.chain().focus().toggleHeading({ level: 1 }).run()" :type="editor.isActive('heading', { level: 1 }) ? 'primary' : ''">H1</el-button>
          <el-button text @click="editor.chain().focus().toggleHeading({ level: 2 }).run()" :type="editor.isActive('heading', { level: 2 }) ? 'primary' : ''">H2</el-button>
          <el-button text @click="editor.chain().focus().toggleBlockquote().run()" :type="editor.isActive('blockquote') ? 'primary' : ''" title="引用">“”</el-button>
          <el-button text @click="editor.chain().focus().toggleCodeBlock().run()" :type="editor.isActive('codeBlock') ? 'primary' : ''" title="代码块">{}</el-button>
          <input type="color" @input="editor.chain().focus().setColor($event.target.value).run()" :value="editor.getAttributes('textStyle').color || '#000000'" class="toolbar-color-picker" title="字体颜色">
          <el-select :model-value="editor.getAttributes('textStyle').fontSize" @change="setFontSize" placeholder="字号" size="small" class="toolbar-select">
            <el-option label="默认" value="" />
            <el-option v-for="size in fontSizes" :key="size" :label="size" :value="size" />
          </el-select>
          <el-button text @click="editor.chain().focus().unsetAllMarks().run()">清除格式</el-button>
        </div>
        <editor-content :editor="editor" class="editor-content-area"/>
      </div>
      <div class="template-section">
        <div class="template-header">创作模板</div>
        <div class="template-buttons">
          <el-button @click="insertTemplate('interview')">面试问题记录</el-button>
          <el-button @click="insertTemplate('offer')">offer筛选</el-button>
          <el-button @click="insertTemplate('review')">简历互助点评</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.editor-page-background { padding: 24px; background-color: #f7f8fa; min-height: 100vh; }
.editor-panel { max-width: 960px; margin: 0 auto; background: #fff; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.08); overflow: hidden; }
.editor-header { padding: 12px 24px; border-bottom: 1px solid #e4e7ed; display: flex; align-items: center; gap: 16px; }
.title-input { flex-grow: 1; }
.title-input :deep(.el-input__inner) { font-size: 24px; font-weight: 500; color: #1d2129; padding-left: 0; }
.header-actions { display: flex; gap: 12px; }
.tiptap-container { padding: 0 24px 24px; }
.editor-toolbar { padding: 8px 0; border-bottom: 1px solid #e4e7ed; margin-bottom: 16px; display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
.editor-content-area { min-height: 400px; }
:deep(.ProseMirror) { outline: none; line-height: 1.7; font-size: 16px; color: #3c4043; }
:deep(.ProseMirror > .is-editor-empty:first-child::before) { content: attr(data-placeholder); float: left; color: #adb5bd; pointer-events: none; height: 0; }
.toolbar-color-picker { width: 28px; height: 28px; border: none; background: none; padding: 2px; cursor: pointer; }
.toolbar-select { width: 100px; }
.template-section { border-top: 1px solid #e5e6eb; padding: 16px 24px; background-color: #fcfcfc; }
.template-header { font-size: 14px; color: #86909c; margin-bottom: 12px; }
.template-buttons { display: flex; gap: 12px; }
</style>